<?php

namespace IDock\Insurance\AMIC\Response;

use IDock\Http\Request;
use IDock\Http\Response;

class AllAMICResponse extends Response
{

    protected $status = '';

    protected $logicStatus = '';

    public function resolve(): Response
    {
        $body = $this->getBody();
        $body = iconv('GBK','UTF-8//IGNORE',$body);

        if ($this->printer) {
            $this->printer = new $this->printer;
        }
        if ($body) {
            $xml = simplexml_load_string($body);
            $body = $this->objectToArray($xml);
            $returnCode = $body['Head']['returnCode'] ?? '';
            $message = $body['Head']['returnMsg'] ?? '';
            $this->setBody($body);
            if ($returnCode != '0000') {
                $this->setError($message);
                return  $this;
            }
        }

        return $this;
    }

    protected function objectToArray($object) {
        if( count($object)==0 )  return trim((string)$object);
        $result = array();
        $object = is_object($object) ? get_object_vars($object) : $object;
        foreach ($object as $key => $val) {
            $val = (is_object($val) || is_array($val)) ? $this->objectToArray($val) : $val;
            $result[$key] = $val;
        }
        return $result;
    }

    /**
     * @return string
     */
    public function getState(): string
    {
        return $this->get('state','');
    }

    /**
     * @return string
     */
    public function getMsg(): string
    {
        return $this->get('msg','');
    }


}
